/**课程表配置文件 */
const { classTable } = require("../input");
/**从零时区获取北京时间 */
const { getNowDay } = require("./utils");
/**处理函数 */
const classFunction = {
  /**判断是开学以来的第几周 ----- 判断的日期由今日时间+偏移量classTable.index决定
   * @returns {Promise<[week, nowdate]>}  返回值为 [第几周, 星期几]
   */
  getNowWeek() {
    return new Promise(async (resolve, reject) => {
      try {
        const schoolTime = classTable.startTime;
        // console.log('开学时间为', schoolTime)
        const startDay = new Date(schoolTime[0], schoolTime[1] - 1, schoolTime[2]); // 是开学时间，月份从0开始
        const startMs = startDay.getTime();
        const nowDay = getNowDay();
        const nowMs = nowDay.getTime();
        const startDays = parseInt(startMs / 86400000);
        const nowDays = parseInt(nowMs / 86400000);
        const totalDays = nowDays - startDays;
        let week = parseInt(totalDays / 7) + 1; //以周一为开学时间，算出来的周数需要+1
        if (totalDays < 0) {
          week = 0; //如果遇到开学时间晚于现在时间的情况，就统一返回0
        }
        let offectDay = nowDay.getDay() + classTable.index; //判断是今日还是明日
        //如果超出限制，就设置为0 周日 ————这一段代码决定了只能支持判断明日，不能判断后天，若有需要再修改叭
        if (offectDay > 6) {
          offectDay = 0;
        }
        const nowdate = parseInt("7123456".charAt(offectDay)); //周几,getDay()出来的是0-6 对应 周日-周六
        console.log("判断开学第几周 - 当前时间为", nowDay, "结果: ", [week, nowdate]);
        resolve([week, nowdate]); //返回第几周和周几
      } catch (error) {
        console.log("获取当前第几周失败", error.message || error);
        reject(error.message || error || "获取当前第几周失败");
      }
    });
  },
  /**判断今日课程，时间数据来源于 getNowWeek
   * @returns {Promise<classList[]>} 返回的是课程数组(为空则代表今日无课)
   */
  getTodayClass() {
    return new Promise(async (resolve, reject) => {
      try {
        const nowDayArrRes = await this.getNowWeek();
        const classList = classTable.list;

        const todayList = []; //存放今日课程
        for (let i = 0; i < classList.length; i++) {
          const element = classList[i];
          const classIndex = element.day.indexOf(nowDayArrRes[1]);
          //                 周数组中是否包含本周              今天是否是这节课的上课周几
          if (element.week.indexOf(nowDayArrRes[0]) > -1 && classIndex > -1) {
            element.jie = element.jie[classIndex]; //把jie转换为今天的节次，抛弃其它天的jie
            todayList.push(element);
          }
        }
        console.log("今日课程表: ", todayList);
        resolve(todayList);
      } catch (error) {
        console.log("判断今日课程失败", error.message || error);
        reject(error.message || error || "判断今日课程出错");
      }
    });
  },
  /**把课程转为字符串
   * @returns {Promise<string>}
   */
  classToString() {
    return new Promise(async (resolve, reject) => {
      try {
        const classLit = await this.getTodayClass();
        const classContent = []; //把课表所需数据以字符串形式放进数组
        classLit.sort((a, b) => a.jie - b.jie); //根据节次排序
        for (let i = 0; i < classLit.length; i++) {
          const element = classLit[i];
          classContent.push(`· 第${element.jie}节: ${element.name} ${element.address}`);
        }
        if (classTable.endWord) {
          classContent.push(`· ${classTable.endWord}`);
        }
        let content = "";
        const day = ["今日", "明日"][classTable.index]; //显示第几天
        if (classContent.length) {
          content = `📕${day}课程提醒: \n${classContent.join("\n")}`;
        } else {
          content = `📕${day}没课哦, 尽情睡懒觉吧~`;
        }
        resolve(content);
      } catch (error) {
        reject(error.message || error);
      }
    });
  },
};

/**导出的课程表模块处理函数 */
module.exports = handleClass = () => {
  //是否在阿里云等国外服务器上运行，默认为运行在阿里云上，所以本地测试时的时间会比北京时间早八小时。当本地测试时下午16点后，实际系统运行的时间已经超过24点了，所以会变成第二天，无需担心，部署到阿里云上就可以了
  return new Promise(async (resolve, reject) => {
    try {
      const res = await classFunction.classToString();
      resolve(res);
    } catch (error) {
      // reject(error.message || error) //不reject，保证就算这一块出错了也不会导致最终无法推送
      resolve(`📕课程表处理失败: ${error.message || error}`);
    }
  });
};
